package com.example.gateway.filter;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;

@Component
public class ErrorHandlerFilter implements GlobalFilter, Ordered {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        return chain.filter(exchange).then(Mono.fromRunnable(() -> {
            // 获取原始响应
            ServerHttpResponse response = exchange.getResponse();
            if (response.getStatusCode() == HttpStatus.NOT_FOUND) {
                // 处理 404 错误
                response.setStatusCode(HttpStatus.NOT_FOUND);
                response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
                response.writeWith(Mono.just(response.bufferFactory().wrap(
                        ApiResponse.error(404, "Resource not found").toString().getBytes(StandardCharsets.UTF_8)
                ));
            } else if (response.getStatusCode() == HttpStatus.INTERNAL_SERVER_ERROR) {
                // 处理 500 错误
                response.setStatusCode(HttpStatus.INTERNAL_SERVER_ERROR);
                response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
                response.writeWith(Mono.just(response.bufferFactory().wrap(
                        ApiResponse.error(500, "Internal server error").toString().getBytes(StandardCharsets.UTF_8)
                ));
            }
        }));
    }

    @Override
    public int getOrder() {
        return -2; // 设置过滤器优先级
    }
}